#include <iostream>
#include <unistd.h>

#include "Mutex.hpp"


int ticket;
pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond =  PTHREAD_COND_INITIALIZER;

void* Ticket(void* arg){
    char *id = (char*)arg;

    while(true){
        pthread_mutex_lock(&mtx);
        if(ticket > 0){
            usleep(1000);
            ticket--;
            printf("%s get a ticket, remain:%d\n", id, ticket);
            pthread_mutex_unlock(&mtx);
            usleep(1000);
        }
        else {
            printf("%s waiting on cond\n", id);
            pthread_cond_wait(&cond,&mtx);//被叫醒了内部自动会给cond的队头元素拿锁
            printf("%s awaked\n", id);
        }
        //被叫醒了内部自动会给cond的队头元素拿锁所以需要解锁
        pthread_mutex_unlock(&mtx);
    }
    return nullptr;
}


int main()
{
    pthread_t t1,t2,t3,t4;

    pthread_create(&t1, nullptr, Ticket, (void*)"thread-1");
    pthread_create(&t2, nullptr, Ticket, (void*)"thread-2");
    pthread_create(&t3, nullptr, Ticket, (void*)"thread-3");
    pthread_create(&t4, nullptr, Ticket, (void*)"thread-4");

    int attribute_ticket = 5;
    while(true)
    {
        sleep(3);
        ticket += attribute_ticket;
        pthread_cond_signal(&cond);
        // pthread_cond_broadcast(&cond);
    }

    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    pthread_join(t3, NULL);
    pthread_join(t4, NULL);

    return 0;
}